package com.example.educationalsystem.common.security.handler;


import com.example.educationalsystem.common.security.config.JWTConfig;
import com.example.educationalsystem.common.security.pojo.SelfUserEntity;
import com.example.educationalsystem.common.security.util.JWTTokenUtil;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.LoginUser;
import com.example.educationalsystem.entity.User;
import com.example.educationalsystem.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 登录成功处理类
 */
@Slf4j
@Component
@Api("用户信息管理")
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private IUserService iUserService;


    /**
     * 登录成功返回结果
     */
    @Override
    @ApiOperation("用户登录")
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {


        // 组装JWT
        SelfUserEntity selfUserEntity = (SelfUserEntity) authentication.getPrincipal();
        String token = JWTTokenUtil.createAccessToken(selfUserEntity);
        token = JWTConfig.tokenPrefix + token;

        User user=iUserService.getById(selfUserEntity.getUserID());

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(selfUserEntity.getUserID());   //id
        loginUser.setUserName(user.getUserName());       //用户名，登录账号
        loginUser.setUserAvatarUrl(user.getUserAvatarUrl());     //头像图片
        loginUser.setUserPhone(user.getUserPhone());         //手机号
        loginUser.setUserIdentity(user.getUserIdentity());       //用户身份
        loginUser.setUserEmail(user.getUserEmail());              //用户邮箱
        loginUser.setUserPermissions(user.getUserPermissions());  //用户权限



        // 封装返回参数
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("status", "200");
        resultData.put("msg", "登录成功");
        resultData.put("token", token);
        resultData.put("loginUser", loginUser);
        ResponseJson.responseSuccessMap(response,resultData);
    }
}
